import productData from '../../components/shopping/productData';

export const cart = {
  state: {
    productList: [],
    cartList: [],
  },
  getters: {
    brands :state=>{
      let brands = state.productList.map(item => item.brand);
      return Array.from(new Set(brands));
    },
    colors :state=>{
      let colors = state.productList.map(item => item.color);
      return Array.from(new Set(colors));
    },
  },
  mutations: {
    //清空购物车
    emptyCart(state){
      state.cartList = [];
    },
    // 添加商品列表
    setProductList (state, data) {
      state.productList = data;
    },
    //添加到购物车
    addCart(state, id){
      const isAdd = state.cartList.find(item => item.id == id);
      if(isAdd){
        isAdd.count++;
      } else {
        state.cartList.push({
          count: 1,
          id
        });
      }
    },
    editCartCount (state, data){
      const product = state.cartList.find(item => item.id == data.id);
      product.count += data.count;
    }
  },
  actions: {
    getProductList(context){
      // 真实环境通过 ajax 获取，这里用异步模拟
      setTimeout(()=>{
        context.commit('setProductList',productData);
      },500);
    },
    buy(context){
      // 真实环境应通过 ajax 提交购买请求后再清空购物列表
      return new Promise(resolve => {
        setTimeout(()=>{
          context.commit('emptyCart');
        },500);
        resolve();
      })
      
    }
  }
}